package com.springmvc.demo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class CookieAndSission {

// 获取 cookie（获取所有）
    @RequestMapping("/getCookie1")
    public String getCookie1(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            System.out.println("cookie为空");
        }
//      1.打印
        Arrays.stream(cookies).forEach(x -> {
            System.out.println(x.getName() + ":" + x.getValue());
        });
//      2.打印
        for(Cookie c : cookies) {
            System.out.println(c.getName() + ":" + c.getValue());
        }

        return "获取cookie成功";

    }
//  获取 cookie（获取一个）
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("lpy") String lpy) {
        return "lpy:" + lpy;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("lpy", "2569");
        return "setSession 成功";
    }

//    获取 session
    @RequestMapping("/getSession1")
    public String getSession1(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object lpy = session.getAttribute("lpy");
        return "登录账户" + lpy;

    }

//
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        Object lpy = session.getAttribute("lpy");
        return "登录账户" + lpy;
    }

//
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute(value = "lpy", required = false) String lpy) {
        return "登录账户" + lpy;
    }


//    获取 header
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("user-Agent");
        return "user_Agent" + userAgent;
    }

//
//    @RequestMapping("/getHeader2")
//    public String getHeader2(@RequestHeader("user-Agent") String userAgent)_{
//        return "userAgent" + userAgent;
//    }



}
